package com.ddwl.goods.service;

import com.ddwl.common.exception.ParamException;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.common.util.UUIDGenerator;
import com.ddwl.goods.dao.SupplierDao;
import com.ddwl.goods.model.Supplier;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.goods.SupplierBo;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.goods.SupplierVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import java.util.List;

/**
 * 供应商
 *
 * @version 1.0.0
 */
@Service
public class SupplierService {


    @Resource
    private SupplierDao supplierdao;

    @Transactional(rollbackFor = Throwable.class)
    public String create(SupplierBo bo) {
        ParamException.isTrue(StringUtil.isNotEmpty(bo.getId()),"id不为空");
        Supplier entity = new Supplier();
        BeanUtils.copyProperties(bo, entity);
        if (StringUtil.isEmpty(entity.getAppId())){
            entity.setAppId(UUIDGenerator.getUUID());
        }
        Supplier supplier = supplierdao.selectOne(entity);
        ParamException.isNotNull(supplier,"appId不能重复");
        //创建商品
        entity.setId(UUIDGenerator.getShortUUID());
        supplierdao.insert(entity);
        return entity.getId();
    }

    /**
     * 查询列表
     * @param bo
     * @return
     */
    public PageVo<SupplierVo> getList(PageBo<SupplierBo> bo) {
        PageHelper.startPage(bo.getPage(), bo.getPageSize(), MySqlUtil.orderBy(bo.getSort(), bo.isAsc()));
        List<Supplier> suppliers = supplierdao.select(BeanConverUtils.convertBean(bo.getParam(), Supplier.class));
        PageInfo<Supplier> supplierPageInfo = new PageInfo<>(suppliers);
        List<SupplierVo> supplierVos = BeanConverUtils.convertBeanList(supplierPageInfo.getList(), SupplierVo.class);
        return new PageVo<>(supplierPageInfo.getTotal(), bo.getPage(), bo.getPageSize(), supplierVos);
    }

    public List<SupplierVo> getList(SupplierBo bo) {
        List<Supplier> suppliers = supplierdao.select(BeanConverUtils.convertBean(bo, Supplier.class));
        return BeanConverUtils.convertBeanList(suppliers, SupplierVo.class);
    }
}

